package com.example.shaketounlock;

import android.app.KeyguardManager;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.IBinder;
import android.os.PowerManager;
import android.os.PowerManager.WakeLock;
import android.util.Log;
import android.widget.Toast;

public class ProximitySensor extends Service implements SensorEventListener {

	private SensorManager mSensorManager;
	private Sensor mSensor;

	private void processStartService(final String tag) {
		Intent intent = new Intent(getApplicationContext(), MyService.class);
		intent.addCategory(tag);
		startService(intent);
	}

	private void processStopService(final String tag) {
		Intent intent = new Intent(getApplicationContext(), MyService.class);
		intent.addCategory(tag);
		stopService(intent);
	}

	@Override
	public IBinder onBind(Intent intent) {

		Log.d("MyService", "onBind");
		return null;
	}

	@Override
	public void onCreate() {

		Log.d("ProximitySensor", "onCreate");

		super.onCreate();
	}

	@Override
	public void onStart(Intent intent, int startId) {
		Toast.makeText(getBaseContext(), "ProximitySensor onCreate",
				Toast.LENGTH_LONG).show();
		mSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
		mSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_PROXIMITY);
		mSensorManager.registerListener(this, mSensor,
				SensorManager.SENSOR_DELAY_NORMAL);
		super.onStart(intent, startId);
	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {

		return super.onStartCommand(intent, flags, startId);
	}

	@Override
	public void onDestroy() {
		mSensorManager.unregisterListener(this);
		super.onDestroy();
	}

	@Override
	public boolean onUnbind(Intent intent) {

		Log.d("MyService", "onUnbind");
		return super.onUnbind(intent);
	}

	@Override
	public void onAccuracyChanged(Sensor sensor, int accuracy) {
		// TODO Auto-generated method stub

	}

	public void onSensorChanged(SensorEvent event) {
		if (event.values[0] == 0) {
			processStopService(SettingData.ShakeService);
		} else {
			processStartService(SettingData.ShakeService);
		}
	}

}